import json
import re

from django import http
from django.contrib.auth import authenticate, login
from django.core.serializers import serialize
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from homes.models import House
from libs.qiniuyun.qiniu_storage import storage
from settings import QINIU_URL
from users.models import User


# 注册
class registerView(View):
    def post(self, request):
        # 1, 获取参数
        username = json.loads(request.body.decode()).get("mobile")
        username = str(username)
        mobile = json.loads(request.body.decode()).get("mobile")
        password = json.loads(request.body.decode()).get("password")
        phonecode = json.loads(request.body.decode()).get("phonecode")

        # 2, 校验参数
        # 2,1 为空校验
        if not all([username, mobile, password, phonecode]):
            return http.JsonResponse({"errno": "400", "errmsg": "参数不全"})

        # 2,3 手机号格式正确
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({"errno": "400", "errmsg": "手机号格式有误"})

        # 2,5 短信验证码正确(下一次完成)
        # 2,5 短信验证码正确
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s" % mobile)
        if phonecode != redis_sms_code.decode():
            return http.JsonResponse({"errno": "400", "errmsg": "短信验证码填写错误"})

        # 3, 数据入库
        # user = User.objects.create(username=user_name, password=pwd, mobile=phone)
        # 可以对密码加密
        user = User.objects.create_user(username=username, mobile=mobile, password=password)
        request.session['username'] = mobile
        request.session.set_expiry(3600 * 24 * 2)

        # 4, 返回响应
        return http.JsonResponse({"errno": "0", "errmsg": "注册成功"})


# 登陆
class sessionView(View):
    # 加载是否登陆
    def get(self, request):
        content = {}
        username = request.session.get('username')
        try:
            user = User.objects.get(mobile=username)
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})
        if username:
            content = {
                "errno": "0",
                "errmsg": "已登录",
                "data": {
                    "name": user.username,
                    'user_id': user.id
                }
            }
        else:
            content = {
                "errno": "4101",
                "errmsg": "未登录"
            }
        return http.JsonResponse(content)

    # 登陆
    def post(self, request):
        mobile = json.loads(request.body.decode()).get('mobile')
        password = json.loads(request.body.decode()).get('password')
        # try:
        #     user=User.objects.get(mobile=mobile)
        # except:
        #     return http.JsonResponse({"errno": "400", "errmsg": "手机号不存在"})

        if not all([mobile, password]):
            return http.JsonResponse({"errno": "400", "errmsg": "参数不全"})

        # 2,2 手机格式
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({"errno": "400", "errmsg": "手机号格式有误"})

        user = authenticate(request, mobile=mobile, password=password)

        if not user:
            return http.JsonResponse({"errno": "400", "errmsg": "账号密码有误"})

        # login(request, user)
        request.session['username'] = mobile
        request.session.set_expiry(3600 * 24 * 2)

        # print(request.session.get('username'))

        # if remembered == 'on':
        #     request.session.set_expiry(3600 * 24 * 2)
        # else:
        #     request.session.set_expiry(0)
        # if not to_url:
        #     to_url='/'
        # response = redirect(to_url)
        # response.set_cookie('username', user.username, max_age=3600 * 24 * 2)

        return http.JsonResponse({"errno": "0", "errmsg": "登录成功"})

    # 退出
    def delete(self, request):
        try:
            del request.session['username']
            return http.JsonResponse({"errno": "0", "errmsg": "已登出"})
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "登出失败"})


# 用户中心
class userInfoView(View):
    def get(self, request):
        content = {}
        username = request.session.get('username')
        try:
            user = User.objects.get(mobile=username)
            if str(user.avatar):
                avatar_url = QINIU_URL + str(user.avatar)
            else:
                avatar_url =''
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})

        content = {
            "data": {
                "avatar_url": avatar_url,
                "mobile": user.mobile,
                "name": user.username
            },
            "errmsg": "OK",
            "errno": "0"
        }

        return http.JsonResponse(content)


#上传头像
class avatarView(View):
    def post(self, request):
        content = {}
        file_name = request.FILES.get('avatar')
        # print(type(file_name),file_name)
        # with open(file_name, "rb") as f:
        avatar_url = storage(file_name.read())
        username = request.session.get('username')
        try:
            User.objects.filter(mobile=username).update(avatar=avatar_url)
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})
        avatar_url = QINIU_URL + avatar_url
        content = {
            "data": {
                "avatar_url": avatar_url
            },
            "errno": "0",
            "errmsg": "头像上传成功"
        }

        return http.JsonResponse(content)
        # return

#修改名字
class nameView(View):
    def put(self,request):
        username = request.session.get('username')
        try:
            name = json.loads(request.body.decode()).get('name')
            # user = User.objects.get(mobile=username)
            User.objects.filter(mobile=username).update(username=name)
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})

        return http.JsonResponse({"errno": "0","errmsg": "修改成功"})


#实名认证
class authView(View):
    def post(self,request):
        username = request.session.get('username')
        try:
            name = json.loads(request.body.decode()).get('real_name')
            id_card = json.loads(request.body.decode()).get('id_card')
            # user = User.objects.get(mobile=username)
            User.objects.filter(mobile=username).update(real_name=name,id_card=id_card)
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})

        return http.JsonResponse({"errno": "0","errmsg": "认证信息保存成功"})

    def get(self,request):
        username = request.session.get('username')
        try:
            # user = User.objects.get(mobile=username)
            user=User.objects.get(mobile=username)
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})

        content = {
            "data": {
                "real_name": user.real_name,
                "id_card": user.id_card
            },
            "errno": "0",
            "errmsg": "头像上传成功"
        }
        return http.JsonResponse(content)


#我的房源
class HousesView(View):
    def get(self,request):
        username = request.session.get('username')
        try:
            user=User.objects.get(mobile=username)
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})

        try:
            houses=House.objects.filter(user_id=user.id)
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "信息有误"})
        # if houses.count()==0:
        #     return http.JsonResponse({"errno": "400", "errmsg": "尚未发布房源"})
        houses_list=[]
        for house in houses:
            house_dict={
                "address": house.address,
                "area_name": house.area.name,
                "ctime": house.create_time,
                "house_id": house.id,
                "img_url":  (QINIU_URL +house.index_image_url),
                "order_count": 0,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "user_avatar": (QINIU_URL +str(user.avatar))
            }
            houses_list.append(house_dict)
            # print(area.name)
        content={
            "errmsg": "获取成功",
            "errno": "0",
            "data": {
                "houses": houses_list
            },
        }
        return http.JsonResponse(content)